package com.yoho.vpm.custom

import android.content.Context
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.trello.rxlifecycle2.android.lifecycle.kotlin.bindToLifecycle
import com.yoho.vpm.R
import com.yoho.vpm.R.attr.pointNormal
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit


/**
 * Created by vpm_miao on 2018/2/9.
 */
class ImageSlider : FrameLayout {


    private var view_page: ViewPager
    private var ll_small_point: LinearLayout
    private var pointNormal: Int
    private var pointSelect: Int
    private var pageChangeDuration: Int
    private var pageHeight: Float
    private var isAutoPlay = true
    private var mCurrent = Int.MAX_VALUE / 2

    private var observeInterval: Disposable? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, def: Int) : super(context, attrs, def) {
        //获取数据
        var typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageSlider, def, 0)
        pageHeight = typedArray.getDimension(R.styleable.ImageSlider_pageHeight, 0f)
        pageChangeDuration = typedArray.getInt(R.styleable.ImageSlider_pageChangeDuration, 3000)
        pointNormal = typedArray.getResourceId(R.styleable.ImageSlider_pointNormal, 0)
        pointSelect = typedArray.getResourceId(R.styleable.ImageSlider_pointSelect, 0)
        typedArray.recycle()
        initView(context, attrs, def)
    }

    init {
        var inflate = LayoutInflater.from(context).inflate(R.layout.image_slider, this, true)
        view_page = inflate.findViewById(R.id.viewPage)
        ll_small_point = inflate.findViewById(R.id.ll_small_point)

    }

    private fun initView(context: Context, attrs: AttributeSet?, def: Int) {
        //初始化point
        initPoints()
        initPages()
    }

    private fun initPages() {
        view_page.adapter = mAdapter
        view_page.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> stop()
                MotionEvent.ACTION_UP -> start()
            }
            false
        }
        view_page.addOnPageChangeListener(object:ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(position: Int) =
                    updateSelectPoint(position%mData.size)

            override fun onPageScrolled(p0: Int, p1: Float, p2: Int) = Unit

            override fun onPageSelected(p0: Int) = Unit
        })
        start()
    }

    //动态更新 Item

    private fun start() {
        observeInterval = Observable.interval(pageChangeDuration.toLong(), pageChangeDuration.toLong(), TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (mData.size > 0 && isAutoPlay) {
                        mCurrent++
                        view_page.currentItem = mCurrent
                    }
                }

    }

    private fun stop() {
        if (observeInterval != null && observeInterval!!.isDisposed) {
            observeInterval!!.dispose()
        }
    }

    //初始化圆点
    private fun initPoints() {
        for (i in 0..mData.size) {
            var view = View(context)
            var params = LinearLayout.LayoutParams(8, 8)
            if (i != 0) {
                params.leftMargin = 5
            }
            view.layoutParams = params
            if (pointNormal == 0) {
                view.setBackgroundResource(R.drawable.bg_point_normal)
            } else {
                view.setBackgroundResource(pointNormal)
            }
            ll_small_point.addView(view)
        }
    }

    //更新红点位置
    private fun updateSelectPoint(position: Int) {
        var childCount = ll_small_point.childCount
        for (i in 0..childCount) {
            var imageView = ll_small_point.getChildAt(i)
            if (i == position) {
                if (pointSelect == 0) {
                    imageView.setBackgroundResource(R.drawable.bg_point_select)
                } else {
                    imageView.setBackgroundResource(pointSelect)
                }
            } else {
                if (pointNormal == 0) {
                    imageView.setBackgroundResource(R.drawable.bg_point_normal)
                } else {
                    imageView.setBackgroundResource(pointNormal)
                }
            }
        }
    }

    private var mData = ArrayList<String>(arrayListOf())

    private val mAdapter by lazy {
        object : PagerAdapter() {
            override fun isViewFromObject(p0: View?, p1: Any?): Boolean = p0 == p1

            override fun getCount(): Int = Int.MAX_VALUE

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                val imageView = ImageView(context)
                val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                imageView.layoutParams = layoutParams
                Glide.with(context).load(mData[position % mData.size]).asBitmap().into(imageView)
                container.addView(imageView)
                return imageView
            }

            override fun destroyItem(container: ViewGroup?, position: Int, obj: Any?) {
                if (obj == null)
                    return
                Glide.clear(obj as View)//核心，解决OOM
                container?.removeView(obj as View?)
            }
        }
    }


    fun setData(data: ArrayList<String>) {
        mData = data
    }

}